package point

import (
	"fmt"

	"github.com/spf13/viper"
)

type WanXIpAllocationPoint struct {
	index int
}

var wanxMode string

func NewWanXIpAllocationPoint() *WanXIpAllocationPoint { return &WanXIpAllocationPoint{} }

func (s *WanXIpAllocationPoint) Get() any {

	var interfaceName string
	if s.index == 0 {
		interfaceName = "eth1"
	} else if s.index == 1 {
		interfaceName = "eth2"
	} else {
		return ""
	}

	// getConnectionUuid := func(iface string) string {
	// 	cmd := exec.Command("nmcli", "connection")
	// 	output, err := cmd.Output()
	// 	if err != nil {
	// 		return ""
	// 	}

	// 	lines := strings.Split(string(output), "\n")

	// 	pattern := `\s*(.*?)\s+\s+(.*?)\s+\s+(.*?)\s+\s+(.*?)\s*$`
	// 	re := regexp.MustCompile(pattern)

	// 	for _, line := range lines {
	// 		if line == "" {
	// 			continue
	// 		}
	// 		parts := re.FindStringSubmatch(line)
	// 		if len(parts) != 5 {
	// 			continue
	// 		}
	// 		// name, uuid, typ, device := parts[1], parts[2], parts[3], parts[4]
	// 		// fmt.Printf("NAME: %s, UUID: %s, TYPE: %s, DEVICE: %s\n", name, uuid, typ, device)

	// 		if parts[4] == iface {
	// 			return parts[2]
	// 		}
	// 	}

	// 	return ""
	// }

	// getConnectionMode := func(uuid string, key string) string {
	// 	if uuid == "" {
	// 		return uuid
	// 	}

	// 	cmd := exec.Command("nmcli", "connection", "show", uuid)
	// 	output, err := cmd.Output()
	// 	if err != nil {
	// 		return ""
	// 	}

	// 	lines := strings.Split(string(output), "\n")

	// 	pattern := `\s*(.*?)\s+\s+(.*?)\s*$`
	// 	re := regexp.MustCompile(pattern)

	// 	for _, line := range lines {
	// 		if line == "" {
	// 			continue
	// 		}
	// 		parts := re.FindStringSubmatch(line)
	// 		if len(parts) != 3 {
	// 			continue
	// 		}
	// 		// fmt.Println("key -->", parts[1])
	// 		// fmt.Println("val -->", parts[2])
	// 		if parts[1] == key {
	// 			return parts[2]
	// 		}
	// 	}

	// 	return ""
	// }

	getConnectionModeByConfigFile := func(interfaceName string) string {
		v := viper.New()
		v.SetConfigName("config")
		v.SetConfigType("yaml")
		v.AddConfigPath("/etc/netplan")

		err := v.ReadInConfig()
		if err != nil {
			fmt.Println("read config file failed, err -->", err)
			return "DHCP"
		}

		if v.GetBool("network.ethernets." + interfaceName + ".dhcp4") {
			return "DHCP"
		}

		return "static"
	}

	// return getConnectionMode(getConnectionUuid(interfaceName), "ipv4.method:")
	return getConnectionModeByConfigFile(interfaceName)
}

func (s *WanXIpAllocationPoint) Set(val ...any) bool {
	if len(val) < 1 {
		return false
	}

	if mode, ok := val[0].(string); ok {
		wanxMode = mode
	}

	return true
}

func (s *WanXIpAllocationPoint) SetRoute(str string) PointInterface {
	s.index = int(str[len("wan")]) - '0'
	return s
}
